import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//等差数列划分 II - 子序列
//测试链接： https://leetcode.cn/problems/arithmetic-slices-ii-subsequence/https://leetcode.cn/problems/arithmetic-slices-ii-subsequence/
public class NumberOfArithmeticSlicesTwo {
    public int numberOfArithmeticSlices(int[] nums) {
        // 优化
        Map<Long, List<Integer>> hash = new HashMap<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            long tmp = (long) nums[i];
            if (!hash.containsKey(tmp))
                hash.put(tmp, new ArrayList<Integer>());
            hash.get(tmp).add(i);
        }
        int[][] dp = new int[n][n];
        int sum = 0;
        for (int j = 2; j < n; j++) // 固定倒数第⼀个数
            for (int i = 1; i < j; i++) // 枚举倒数第⼆个数
            {
                long a = 2L * nums[i] - nums[j];
                if (hash.containsKey(a)) {
                    for (int k : hash.get(a))
                        if (k < i)
                            dp[i][j] += dp[k][i] + 1;
                        else
                            break; // ⼩优化
                }
                sum += dp[i][j];
            }
        return sum;
    }
}
